/**
 */

package com.bei_en.teacher.third.pay.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bei_en.common.util.SMS.ali.SMS;
import com.bei_en.common.web.JsonResult;
import com.bei_en.teacher.admin.model.order.condition.OrderBasicCondition;
import com.bei_en.teacher.admin.model.order.vo.OrderBasicVo;
import com.bei_en.teacher.admin.service.order.OrderBasicService;
import com.bei_en.teacher.third.pay.bean.AliPayNotifyResult;
import com.bei_en.teacher.third.pay.bean.WxPayDto;
import com.bei_en.teacher.third.pay.bean.WxPayResult;
import com.bei_en.teacher.third.pay.bean.Mwxpay.MpayBean;
import com.bei_en.teacher.third.pay.common.Key;
import com.bei_en.teacher.third.pay.common.Util;
import com.bei_en.teacher.third.pay.web.alipay.AlipayNotify;

/**
 * @author Guocg
 *
 */
@Controller
@RequestMapping(value = "/pay/weixin")
public class LinWeixinController extends BaseController {

    public static final int PAY_TIME = 30;// 支付有效时间,30分钟
//    public static String notify_url1 = "http://teachershanglv.com:9999/api/pay/weixin/notify";// 服务器异步通知页面路径
    public static String notify_url2 = "http://www.ekaojiaoshi.com:8080/pay/weixin/notify";// 服务器异步通知页面路径
    @Autowired
    OrderBasicService orderBasicService;
    @RequestMapping("/notify")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request,
	    HttpServletResponse response) throws IOException {
    	
    	// 把如下代码贴到的你的处理回调的servlet 或者.do 中即可明白回调操作
    	log.debug("微信支付回调数据开始");
    	System.out.println("ssssssssssssssssssssssssssss");
    	// 示例报文
    	// String xml =
    	// "<xml><appid><![CDATA[wxb4dc385f953b356e]]></appid><bank_type><![CDATA[CCB_CREDIT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1228442802]]></mch_id><nonce_str><![CDATA[1002477130]]></nonce_str><openid><![CDATA[o-HREuJzRr3moMvv990VdfnQ8x4k]]></openid><out_trade_no><![CDATA[1000000000051249]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[1269E03E43F2B8C388A414EDAE185CEE]]></sign><time_end><![CDATA[20150324100405]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1009530574201503240036299496]]></transaction_id></xml>";
    	String inputLine;
    	String notityXml = "";
    	String resXml = "";

    	try {
    	    while ((inputLine = request.getReader().readLine())!=null) {
    		notityXml += inputLine;
    	    }
    	    request.getReader().close();
    	} catch (Exception e) {
    	    e.printStackTrace();
    	}

    	log.debug("接收到的报文："+notityXml);
    	if (notityXml.equals("")) {
    	    resXml = "<xml>"+"<return_code><![CDATA[FAIL]]></return_code>"
    		    +"<return_msg><![CDATA[报文为空]]></return_msg>"+"</xml> ";
    	    log.error("报文为空");
    	    /* BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    	     out.write(resXml.getBytes());
    	     out.flush();
    	     out.close();*/
    	    return null;
    	}

    	Map<String, String> m = Util.parseXmlToList2(notityXml);
    	WxPayResult wpr = new WxPayResult();
    	if (m.isEmpty()) {
    	    resXml = "<xml>"+"<return_code><![CDATA[FAIL]]></return_code>"
    		    +"<return_msg><![CDATA[报文为空]]></return_msg>"+"</xml> ";
    	    log.error("报文为空");
    	    /* BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    	     out.write(resXml.getBytes());
    	     out.flush();
    	     out.close();*/
    	    return resXml;
    	}


    	log.debug("自主校验成功");

//    	wpr.setAppid(m.get("appid"));
//    	wpr.setBankType(m.get("bank_type"));
//    	wpr.setCashFee(m.get("cash_fee"));
//    	wpr.setFeeType(m.get("fee_type"));
//    	wpr.setIsSubscribe(m.get("is_subscribe"));
//    	wpr.setMchId(m.get("mch_id"));
//    	wpr.setNonceStr(m.get("nonce_str"));
//    	wpr.setOpenid(m.get("openid"));
    	wpr.setOutTradeNo(m.get("out_trade_no"));
    	wpr.setResultCode(m.get("result_code"));
    	wpr.setReturnCode(m.get("return_code"));
//    	wpr.setSign(m.get("sign"));
//    	wpr.setTimeEnd(m.get("time_end"));
    	wpr.setTotalFee(m.get("total_fee"));
//    	wpr.setTradeType(m.get("trade_type"));
//    	wpr.setTransactionId(m.get("transaction_id"));
//    	wpr.setAttach(m.get("attach"));


    	if ("SUCCESS".equals(wpr.getResultCode())) {
    		String code =wpr.getOutTradeNo().split("-")[0];
    		OrderBasicCondition orderBasicCondition=new OrderBasicCondition();
    		orderBasicCondition.setOrderNum(code);
    		 List<OrderBasicVo>orderBasicVos= orderBasicService.findOrderBasicPage(orderBasicCondition);
    		if(!orderBasicVos.isEmpty()){
    			OrderBasicVo orderBasicVo=orderBasicVos.get(0);
    			orderBasicVo.setPaymentNumber(wpr.getTransactionId());
    			orderBasicVo.setPaymentGateway(1+"");	
    			orderBasicVo.setPaymentTime((int)(new Date().getTime()/1000));
    			orderBasicVo.setStatus(2);
    			orderBasicService.updateSelective(orderBasicVo);
    		}else{
    		   	resXml = "<xml>"+"<return_code><![CDATA[FAIL]]></return_code>"
    	    		    +"<return_msg><![CDATA[支付失败]]></return_msg>"+"</xml> ";
    			return resXml;
    		}
    		
    		
    	    resXml = "<xml>"+"<return_code><![CDATA[SUCCESS]]></return_code>"
    		    +"<return_msg><![CDATA[OK]]></return_msg>"+"</xml> ";
    	} else {
    	    resXml = "<xml>"+"<return_code><![CDATA[FAIL]]></return_code>"
    		    +"<return_msg><![CDATA[支付失败]]></return_msg>"+"</xml> ";
    	    log.error("支付失败");
    	    /*BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    	    out.write(resXml.getBytes());
    	    out.flush();
    	    out.close();*/
    	 }
    	
		return resXml;
    }
    
    @RequestMapping("/acceptNotify")
    public JsonResult acceptNotify(HttpServletRequest request, Model model, HttpServletResponse response)
	    {
    	return null;
	    }
    
}
